<template>
  <div class="background">
    <!-- 返回按钮 -->
    <div class="return-button">
      <el-button type="text" @click="goBack">返回</el-button>
    </div>

    <div class="container">
      <el-card class="box-card">
        <h1 class="title">关系模式输入</h1>
        <el-form :model="form" :rules="rules" ref="form" label-width="120px" @submit.native.prevent="submitForm">
          <!-- 关系模式名称 -->
          <el-form-item label="关系模式名称" prop="relationName">
            <el-input v-model="form.relationName" placeholder="请输入关系模式名称" clearable></el-input>
          </el-form-item>

          <!-- 属性集 R -->
          <el-form-item label="属性集 R" prop="attributes">
            <el-input v-model="form.attributes" placeholder="请输入属性集，用逗号分隔（例如：A,B,C 或 甲,乙,丙）" clearable></el-input>
          </el-form-item>

          <!-- 函数依赖集 F -->
          <el-form-item label="函数依赖集 F" prop="functionalDependencies">
            <el-input type="textarea" v-model="functionalDependenciesDisplay" placeholder="请选择或输入函数依赖集" :rows="4" readonly></el-input>
            <div style="margin-top: 10px;">
              <el-select v-model="selectedLeft" placeholder="请选择左侧属性" style="width: 45%;">
                <el-option v-for="attr in attributesArray" :key="attr" :label="attr" :value="attr"></el-option>
              </el-select>
              <span style="padding: 0 10px;">→</span>
              <el-select v-model="selectedRight" placeholder="请选择右侧属性" style="width: 45%;">
                <el-option v-for="attr in attributesArray" :key="attr" :label="attr" :value="attr"></el-option>
              </el-select>
              <el-button type="primary" @click="addDependency" style="margin-top: 10px;">添加依赖</el-button>
            </div>
            <!-- 显示已添加的函数依赖并提供删除按钮 -->
            <div v-if="dependencies.length" style="margin-top: 10px;">
              <div v-for="(dependency, index) in dependencies" :key="index" style="display: flex; align-items: center; margin-bottom: 5px;">
                <span>{{ dependency }}</span>
                <el-button type="text" @click="removeDependency(index)" style="margin-left: auto;">删除</el-button>
              </div>
            </div>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" native-type="submit">提交</el-button>
          </el-form-item>
        </el-form>

        <!-- 提交结果 -->
        <div v-if="submitted && !error" class="result">
          <h2>提交结果</h2>
          <el-divider></el-divider>
          <p><strong>关系模式名称:</strong> {{ form.relationName }}</p>
          <p><strong>属性集 R:</strong> {{ form.attributes }}</p>
          <p><strong>函数依赖集 F:</strong></p>
          <pre>{{ functionalDependenciesDisplay }}</pre>
        </div>
        <div v-if="error" class="error">{{ error }}</div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { addattri } from '@/api/rsa';
import { addfds } from '@/api/rsfds';
import { createsche } from '@/api/rs';

export default {

  data() {
    return {
      form: {
        relationName: '',
        attributes: '',
        functionalDependencies: ''
      },
      submitted: false,
      error: '',
      selectedLeft: '',
      selectedRight: '',
      dependencies: [], // 存储所有函数依赖
      attri: {
        ua: null,
        ub: null,
        uc: null,
        ud: null,
        ue: null,
        uf: null,
        ug: null,
        uh: null,
        ui: null,
        uj: null,
        uk: null,
        ul: null,
        un: null,
        um: null
      },
      fd: {
        fal: null,
        far: null,
        fbl: null,
        fbr: null,
        fcl: null,
        fcr: null,
        fdl: null,
        fdr: null,
        fel: null,
        fer: null,
        ffl: null,
        ffr: null,
        fgl: null,
        fgr: null
      },
      uid:'',
      fid:'',
      rules: {
        relationName: [
          { required: true, message: '请输入关系模式名称', trigger: 'blur' }
        ],
        attributes: [
          { required: true, message: '请输入属性集', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5A-Za-z,]+$/, message: '请输入有效的属性集（仅支持字母、汉字和逗号）', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    attributesArray() {
      if (!this.form.attributes) return [];
      return this.form.attributes.split(',').map(attr => attr.trim());
    },
    functionalDependenciesDisplay() {
      return this.dependencies.join('\n') || '无';
    }
  },
  methods: {
    addDependency() {
      if (this.selectedLeft && this.selectedRight) {
        const newDependency = `${this.selectedLeft}→${this.selectedRight}`;
        this.dependencies.push(newDependency);
        this.form.functionalDependencies = this.dependencies.join('\n');
        this.selectedLeft = '';
        this.selectedRight = '';
      } else {
        this.$message.error('请选择左侧和右侧属性');
      }
    },
    removeDependency(index) {
      this.dependencies.splice(index, 1);
      this.form.functionalDependencies = this.dependencies.join('\n');
    },
    async submitForm() {
    try {
      // 验证表单
      const valid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => {
          resolve(valid);
        });
      });

      if (!valid) {
        this.error = '请检查输入的信息是否符合要求';
        return;
      }

      this.submitted = true;
      this.error = '';

      // 处理属性集分配
      const attributesArray = this.attributesArray; // 获取用户输入的属性集
      const keys = Object.keys(this.attri); // 获取 attri 对象的所有键

      // 清空之前的赋值
      for (let key of keys) {
        this.attri[key] = null;
      }

      // 依次赋值
      attributesArray.forEach((attr, index) => {
        if (index < keys.length) {
          this.attri[keys[index]] = attr;
        }
      });

      console.log("检查");
      console.log(this.attri);

      // 调用 addattri 并等待响应
      const attriResponse = await addattri(this.attri);
      this.uid = attriResponse.data.uid;
      console.log(this.uid);

      // 处理函数依赖集分配
      const dependencies = this.dependencies; // 获取用户输入的函数依赖集
      const keyst = Object.keys(this.fd); // 获取 fd 对象的所有键

      // 清空之前的赋值
      for (let key of keyst) {
        this.fd[key] = null;
      }

      // 依次赋值
      dependencies.forEach((dependency, index) => {
        const parts = dependency.split('→');
        if (parts.length === 2) {
          const leftKey = keyst[2 * index]; // 左侧属性对应的键
          const rightKey = keyst[2 * index + 1]; // 右侧属性对应的键
          if (leftKey && rightKey) {
            this.fd[leftKey] = parts[0].trim();
            this.fd[rightKey] = parts[1].trim();
          }
        }
      });

      console.log(this.uid);
      console.log("在哪里");

      // 调用 addfds 并等待响应
      const fdsResponse = await addfds(this.fd);
      this.fid = fdsResponse.data.fid;
      console.log(this.fid);

      // 调用 createsche 并等待响应
      await createsche(this.form.relationName, this.uid, this.fid).then(() => {
        this.$message({
          message: '新建关系模式成功',
          type: 'success'
        });
        setTimeout(() => {
          this.$router.push('/SCEI/allsche'); // 转到数据库界面
        }, 2000); // 3000 毫秒 = 3 秒
      }).catch(error => {
        console.log(error);
      });
    } catch (error) {
      console.log(error);
      this.error = '提交过程中出现错误，请稍后再试';
    }
  },
    goBack() {
      
      this.$router.go(-1); // 返回上一页
    }
  }
};
</script>

<style scoped>
.background {
  min-height: 100vh;
  background: linear-gradient(135deg, #aa72e6, #5782cd);
  padding: 20px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.box-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  background-color: rgba(255, 255, 255, 0.9);
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.result {
  margin-top: 30px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.error {
  color: red;
  margin-top: 20px;
}
.return-button {
  position: absolute;
  top: 50px;
  right: 250px;
}
</style>